<template>
    <div class="store-main store-main-not">
        <div class="store-main-content">
            <div class="store-header">
                积分商城功能{{ form.status == 1 ? '已启用' : '已关闭' }}
                <el-popconfirm
                    icon="WarningFilled"
                    placement="top"
                    width="200px"
                    :title="switchTitle"
                    :disabled="isDisabled"
                    @confirm="confirmSwitch">
                    <template #reference
                        ><el-switch
                            class="custom-switch"
                            v-model="form.status"
                            :disabled="isDisabled"
                            :active-value="1"
                            :inactive-value="2"
                            :before-change="handleBeforeChange" /></template
                ></el-popconfirm>
            </div>
            <div class="store-btns">
                <AddGoodSpec v-if="!isDisabled" @handle-confirm="queryCouponListHandler" :query="form"></AddGoodSpec>
                <el-button @click="handleRouter">兑换记录</el-button>
            </div>
            <el-table :data="tableList" style="margin-top: 20px">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <div class="custom-goods-name" v-if="prop === 'goodsName'">
                            <el-image
                                style="width: 40px; height: 40px; min-width: 40px; margin-right: 4px"
                                :src="row?.materialSrc?.[0]?.materialSrc || row?.goodsImg"
                                fit="fill"></el-image>
                            <el-tooltip effect="dark" :content="row.goodsName" placement="top">
                                <span class="custom-goods-name-span">{{ row.goodsName }}</span>
                            </el-tooltip>
                        </div>
                        <div v-if="prop === 'operations'">
                            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-popconfirm
                                placement="top"
                                width="250px"
                                title="确定要删除吗？"
                                @confirm="handleRemove(row)"
                                confirm-button-text="确定"
                                cancel-button-text="取消">
                                <template #reference>
                                    <el-button size="small">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                        <!-- todo:兑换价规格的怎么样展示，问下产品 -->
                        <div v-if="prop === 'skuInfo'">
                            <div v-for="item in row.skuInfo" :key="item.id" class="custom-number-small-box">
                                <span>{{ item?.specAttr?.map(item => item.attributeValue)?.join(';') }}</span>
                                <el-tag class="custom-point-tag">{{ item.points / 100 }}积分</el-tag>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="formData.perPage"
                    :current-page="formData.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
            <!-- <div class="form-footer" v-if="!isDisabled">
                <el-button type="primary" @click="handleConfirm">保存</el-button>
            </div> -->
        </div>
        <EditGoodSpec ref="editGoodSpec" @handle-confirm="queryCouponListHandler" :query="form"></EditGoodSpec>
    </div>
</template>

<script setup>
import { onUnmounted, onMounted, reactive, ref, unref, computed } from 'vue';
import { setLayout, resetLayout } from '@/hooks/layout';
import AddGoodSpec from './addGoodSpec.vue';
import EditGoodSpec from './editGoodSpec.vue';
import request from '@/request/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagination from '@/components/Pagination.vue';
import { useRouter, useRoute } from 'vue-router';
import { debounce } from 'lodash';
import store from '@/store/index';

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
// 积分商城编辑point_mail:edit 积分设置编辑point_base:edit
const isDisabled = computed(() => {
    return !permissions.has('point_mail:edit');
});

const router = useRouter();

const editGoodSpec = ref();
const form = reactive({
    status: null,
    authScrm: 1,
    isSwitch: false,
    points: 100,
    rmb: null,
    perGroupAmount: null,
    producerPoints: null,
    isOn: 2,
    deduction: 100,
    suitGoods: 1,
    selectedGoods: []
});
const formData = reactive({
    page: 1,
    perPage: 10
});
const totalCount = ref(0);
let tableList = reactive([]);
// const tableColumns = reactive([
//     { label: '商品类型', prop: 'goodsTypeName', minWidth: '120' },
//     { label: '商品名称', prop: 'goodsName', minWidth: '320' },
//     { label: '价格（元）', prop: 'price', minWidth: '120' },
//     { label: '剩余数量', prop: 'restStock', minWidth: '150' },
//     { label: '兑换价', prop: 'pointsText', minWidth: '150' }, // todo:兑换价格
//     { label: '来源店铺', prop: 'shopInfoText', minWidth: '120' },
//     { label: '操作', prop: 'operations', width: '150', fixed: 'right' }
// ]);
const tableColumns = computed(() => {
    const columns = [
        { label: '商品类型', prop: 'goodsTypeName', width: '90' },
        { label: '商品名称', prop: 'goodsName', minWidth: '300' },
        { label: '价格（元）', prop: 'price', minWidth: '120' },
        { label: '剩余数量', prop: 'restStock', minWidth: '150' },
        { label: '兑换价', prop: 'pointsText', minWidth: '150' }, // todo:兑换价格
        { label: '来源店铺', prop: 'shopInfoText', minWidth: '120' }
    ];
    if (!isDisabled.value) {
        columns.push({ label: '操作', prop: 'operations', width: '150', fixed: 'right' });
    }
    return columns;
});

const getDetail = async () => {
    const { data } = await request('pointsConfig');
    const { perGroupAmount, producerPoints, switch: isSwitch } = data?.pointProducer?.[0]?.config || {};
    form.perGroupAmount = perGroupAmount !== null ? perGroupAmount / 100 : null;
    form.producerPoints = producerPoints !== null ? producerPoints / 100 : null;
    form.points = (data?.pointConsumer?.[0]?.config?.points || 10000) / 100; // todo:默认情况下会给默认积分吗
    form.rmb = (data?.pointConsumer?.[0]?.config?.rmb || 100) / 100;
    form.status = data?.pointGoodsMail?.status;
    form.authScrm = data?.pointGoodsMail?.auth_Scrm;
    form.switch = isSwitch;
    form.isOn = data?.pointDeduction?.isOn;
    form.deduction = (data?.pointDeduction?.deduction || 10000) / 100;
    form.suitGoods = data?.pointDeduction?.suitGoods;
    form.selectedGoods = data?.pointDeduction?.selectedGoods || [];
};
const handleConfirm = async () => {
    const { code } = await request('pointsSaveConfig', {
        authScrm: form.authScrm,
        pointProducer: [
            {
                name: 'order_amount',
                config: {
                    switch: form.switch,
                    perGroupAmount: form.perGroupAmount !== null ? Math.round(form.perGroupAmount * 100) : null,
                    producerPoints: form.producerPoints !== null ? Math.round(form.producerPoints * 100) : null
                }
            }
        ],
        pointConsumer: [
            {
                name: 'point_consumer',
                config: {
                    rmb: form.rmb !== null ? Math.round(form.rmb * 100) : null,
                    points: form.points !== null ? Math.round(form.points * 100) : null
                }
            }
        ],
        pointGoodsMail: {
            status: form.status == 2 ? 1 : 2
        },
        pointDeduction: {
            isOn: form.isOn,
            deduction: form.deduction !== null ? Math.round(form.deduction * 100) : null, //可抵扣比例
            suitGoods: form.suitGoods, //适用商品类型 1全部商品参与，此时selectedGoods 传递为空 2 部分商品参与 3 部分商品不参与
            selectedGoods: form.selectedGoods
        }
    });
    if (code !== 0) {
        return;
    }
    // ElMessage({
    //     type: 'success',
    //     message: `积分商城已${form.status == 1 ? '启用' : '关闭'}`
    // });
};

const handleRouter = () => {
    router.push({
        path: '/point/mail/record'
    });
};

const handleEdit = async row => {
    // todo:编辑
    editGoodSpec?.value?.handleEdit(row);
};

const handleRemove = async ({ id }) => {
    // todo:删除
    await request('pointsGoodsRemove', {
        id
    });
    ElMessage({
        type: 'success',
        message: '删除成功'
    });
    queryCouponListHandler();
};

const handleBeforeChange = async () => {
    // if (form.status == 2) {
    //     return true;
    // }
    // return await ElMessageBox.confirm('关闭后，则积分商城的商品全部清除，确定关闭吗？', '提示信息', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    // })
    //     .then(() => {
    //         return true;
    //     })
    //     .catch(() => {
    //         return false;
    //     });
    return false;
};
const switchTitle = computed(() => {
    return form.status == 1 ? '确定关闭吗？' : '确定开启吗？';
});
const confirmSwitch = async () => {
    await handleConfirm();
    form.status = form.status == 2 ? 1 : 2;
};
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    formData.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    formData.page = 1;
    formData.perPage = perPage;
    queryCouponListHandler();
};

const queryCouponListHandler = async () => {
    const { data } = await request('pointGoodsList', formData);
    tableList.length = 0;
    Object.assign(
        tableList,
        (data?.list || []).map(item => {
            if (item.goodsMinPrice === undefined && item.goodsMaxPrice === undefined) {
                item.price = '-';
            } else if (item.goodsMinPrice === item.goodsMaxPrice) {
                item.price = `￥${item.goodsMinPrice / 100}`;
            } else {
                item.price = `￥${item.goodsMinPrice / 100}~${item.goodsMaxPrice / 100}`;
            }
            item.shopInfoText = item?.shopInfo?.shopName;
            const { pointsConsumerType, limitConfig } = item.pointsConfig;
            if (item.goodsType == 1) {
                if (item.skuInfo && item.skuInfo.length > 0) {
                    item.skuInfo.sort((prev, current) => prev.skuPrice - current.skuPrice);
                    const minPriceSku = item.skuInfo[0];
                    if (minPriceSku) {
                        if (pointsConsumerType != 1) {
                            item.pointsText = minPriceSku.money
                                ? `${minPriceSku.money / 100}元+${minPriceSku.points / 100}积分`
                                : `${minPriceSku.points / 100}积分`;
                        } else {
                            item.pointsText = `${minPriceSku.consumerPoints / 100}积分`;
                        }
                    }
                } else {
                    item.pointsText = '';
                }
            } else {
                item.pointsText = item.money
                    ? `${item.money / 100}元+${item.points / 100}积分`
                    : `${item.points / 100}积分`;
            }
            // todo:商品类型
            const goodTypes = ['商城商品', '优惠券', '抽奖机会'];
            item.goodsTypeName = goodTypes[item.goodsType - 1];
            if (item.goodsType != 3) {
                item.restStock = item.goodsStock;
            } else {
                const { totalUnlimit, totalExchange } = limitConfig || {};
                item.restStock = totalUnlimit == 1 ? '无限制' : totalExchange;
            }
            return item;
        })
    );
    totalCount.value = data?.totalCount;
};

onMounted(() => {
    getDetail();
    queryCouponListHandler();
    setLayout('custom-rule-store-layout');
});
onUnmounted(() => {
    resetLayout('custom-rule-store-layout');
});
</script>

<style lang="scss">
.custom-rule-store-layout {
    padding: 0 !important;
    .el-input-number .el-input__inner {
        text-align: left;
    }
}
</style>
<style lang="scss" scoped>
.store-main {
    position: relative;
    min-height: calc(100vh - 190px);
    &-content {
        overflow-y: auto;
        max-height: calc(100vh - 240px);
        padding: 24px;
    }
    .store-header {
        background: #fffaf9;
        border: 1px solid #facaa8;
        display: flex;
        align-items: center;
        height: 48px;
        padding-left: 16px;
        margin-bottom: 20px;
    }

    .store-btns {
        display: flex;
        justify-content: flex-end;
        & > div {
            margin-right: 8px;
        }
    }

    .form-footer {
        position: absolute;
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% + 31px);
        height: 70px;
        background-color: #fff;
        bottom: -64px;
        left: -15px;
        box-shadow: 0px 0px 10px 0px rgb(212 212 212 / 50%);
        border-radius: 2px;
        z-index: 1;
        .el-button {
            width: 80px;
        }
    }
    .custom-goods-name {
        display: inline-flex;
        align-items: center;
        width: 100%;
        &-span {
            display: -webkit-box;
            max-width: calc(100% - 45px);
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }
    }

    .custom-point-tag {
        margin-left: 5px;
        border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
        color: var(--el-disabled-text-color);
        background-color: var(--el-disabled-bg-color);
        border-color: var(--el-disabled-border-color);
        /* box-shadow: 0 0 0 1px var(--el-disabled-border-color) inset; */
    }

    .custom-number-small {
        width: 80px;
        margin: 0 4px;
    }

    .custom-number-small-box {
        &:not(:first-of-type) {
            margin-top: 10px;
        }
    }

    .custom-switch {
        margin-left: 5px;
    }
}
.store-main-not {
    min-height: calc(100vh - 145px);
}
</style>
